package com.araim.rringtone.db;

import java.util.ArrayList;

import com.araim.rringtone.RingtoneInfo;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class RandomRingtoneDatabase extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "araim.RandomRingtone";
	private static final int DATABASE_VERSION = 1;

	public RandomRingtoneDatabase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE ringtones (id INTEGER PRIMARY KEY, name TEXT not null ,uri TEXT not null)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE ringtones");
		db.execSQL("CREATE TABLE ringtones (id INTEGER PRIMARY KEY, name TEXT not null ,uri TEXT not null)");
	}

	public void insertRingtone(RingtoneInfo ri) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.insert("ringtones", "", ri.getContentValues());
		db.close();
	}

	public void clear() {
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("DELETE FROM ringtones");
	}

	public void delete(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.execSQL("DELETE FROM ringtones WHERE id = ?", new Object[] { id });
	}

	public RingtoneInfo[] getAllRingtonesArray() {
		return getAllRingtones().toArray(new RingtoneInfo[0]);
	}

	public ArrayList<RingtoneInfo> getAllRingtones() {
		SQLiteDatabase db = this.getWritableDatabase();
		db.close();
		db = this.getReadableDatabase();
		Cursor c = db.query("ringtones", new String[] { "id", "name", "uri" },
				null, null, null, null, null);
		ArrayList<RingtoneInfo> ringtones = new ArrayList<RingtoneInfo>();
		if (c.moveToFirst()) {
			while (!c.isAfterLast()) {
				RingtoneInfo r = new RingtoneInfo();
				r.setId(c.getInt(0));
				r.setName(c.getString(1));
				r.setUri(c.getString(2));
				ringtones.add(r);
				c.moveToNext();
			}
		}
		db.close();
		return ringtones;
	}

}
